class CaptchaGenerator {
  constructor() {
    this.width = 120
    this.height = 40
    this.fontSize = 24
  }

  // 生成随机4位数字
  generateCode() {
    return Math.floor(1000 + Math.random() * 9000).toString()
  }

  // 生成随机颜色
  getRandomColor() {
    const r = Math.floor(Math.random() * 256)
    const g = Math.floor(Math.random() * 256)
    const b = Math.floor(Math.random() * 256)
    return `rgb(${r},${g},${b})`
  }

  // 生成浅色背景
  getLightColor() {
    const r = Math.floor(Math.random() * 100) + 200
    const g = Math.floor(Math.random() * 100) + 200
    const b = Math.floor(Math.random() * 100) + 200
    return `rgb(${r},${g},${b})`
  }

  // 生成干扰线
  generateInterferenceLines() {
    let lines = ''
    for (let i = 0; i < 3; i++) {
      const x1 = Math.random() * this.width
      const y1 = Math.random() * this.height
      const x2 = Math.random() * this.width
      const y2 = Math.random() * this.height
      const color = this.getRandomColor()
      lines += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1"/>`
    }
    return lines
  }

  // 生成干扰点
  generateInterferencePoints() {
    let points = ''
    for (let i = 0; i < 20; i++) {
      const cx = Math.random() * this.width
      const cy = Math.random() * this.height
      const color = this.getRandomColor()
      points += `<circle cx="${cx}" cy="${cy}" r="1" fill="${color}"/>`
    }
    return points
  }

  // 生成验证码图片
  generate() {
    // 生成验证码
    const code = this.generateCode()
    const backgroundColor = this.getLightColor()

    // 生成文字元素
    let textElements = ''
    for (let i = 0; i < code.length; i++) {
      const x = 20 + i * 20
      const y = this.height / 2
      const color = this.getRandomColor()
      const rotation = (Math.random() - 0.5) * 30 // 角度转换

      textElements += `<text x="${x}" y="${y}" fill="${color}" font-family="Arial" font-size="${this.fontSize}" text-anchor="middle" dominant-baseline="middle" transform="rotate(${rotation} ${x} ${y})">${code[i]}</text>`
    }

    // 生成SVG
    const svg = `<?xml version="1.0" encoding="UTF-8"?>
    <svg width="${this.width}" height="${this.height}" xmlns="http://www.w3.org/2000/svg">
      <rect width="${this.width}" height="${this.height}" fill="${backgroundColor}"/>
      ${this.generateInterferenceLines()}
      ${this.generateInterferencePoints()}
      ${textElements}
    </svg>`

    return {
      code,
      image: Buffer.from(svg),
    }
  }
}

module.exports = new CaptchaGenerator()
